///
/// 表单项组件
/// 参照Element UI的Form-Item控件实现
import 'package:flutter/material.dart';

import '../../core/elegance_theme.dart';
import 'e_form.dart';

/// 表单项组件
class EFormItem extends StatefulWidget {
  const EFormItem({
    super.key,
    required this.prop,
    required this.child,
    this.label,
    this.labelWidth,
    this.required = false,
    this.disabled = false,
    this.rules,
    this.error,
    this.showMessage = true,
    this.inlineMessage = false,
  });

  final String prop;
  final Widget child;
  final String? label;
  final double? labelWidth;
  final bool required;
  final bool disabled;
  final List<EFormRule>? rules;
  final String? error;
  final bool showMessage;
  final bool inlineMessage;

  @override
  State<EFormItem> createState() => _EFormItemState();
}

class _EFormItemState extends State<EFormItem> {
  @override
  void initState() {
    super.initState();
    // 在initState中初始化，但不获取表单模型
  }

  @override
  void didUpdateWidget(covariant EFormItem oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 属性变化时，让build方法自动处理
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 依赖变化时，让build方法自动处理
  }

  @override
  void dispose() {
    super.dispose();
  }

  /// 触发验证
  void validate([String? trigger]) {
    final formModel = FormModelProvider.maybeOf(context);
    if (formModel == null) return;
    final value = formModel.getField(widget.prop);
    formModel.validateField(widget.prop, value?.toString(), trigger: trigger);
  }

  /// 清除验证状态
  void clearValidate() {
    final formModel = FormModelProvider.maybeOf(context);
    if (formModel == null) return;
    formModel.validateStates[widget.prop] = EFormValidateState.initial;
    formModel.errorMessages.remove(widget.prop);
  }

  /// 获取标签宽度
  double _getLabelWidth(EFormModel? formModel) {
    if (widget.labelWidth != null) {
      return widget.labelWidth!;
    }
    if (formModel != null && formModel.layout == EFormLayout.horizontal) {
      return 100.0;
    }
    // 在垂直布局中也使用合理的宽度，避免使用infinite导致布局问题
    return 0.0;
  }

  /// 构建标签组件
  Widget _buildLabel() {
    if (widget.label == null) {
      return const SizedBox();
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (widget.required) ...[
          Text(
            '*',
            style: TextStyle(
              color: EleganceTheme.of(context).errorColor,
              fontSize: 12,
            ),
          ),
          const SizedBox(width: 4),
        ],
        Text(widget.label!),
      ],
    );
  }

  /// 获取错误信息组件
  Widget? _buildErrorMessage(EFormModel? formModel) {
    if (!widget.showMessage) return null;

    String? errorText;
    if (widget.error != null && widget.error!.isNotEmpty) {
      errorText = widget.error;
    } else if (formModel != null) {
      errorText = formModel.errorMessages[widget.prop];
    }

    if (errorText == null) return null;

    return Container(
      margin: EdgeInsets.only(top: widget.inlineMessage ? 0 : 8),
      child: Text(
        errorText,
        style: TextStyle(
          color: EleganceTheme.of(context).errorColor,
          fontSize: 12,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  /// 构建水平布局
  Widget _buildHorizontalLayout(EFormModel? formModel) {
    final labelWidth = _getLabelWidth(formModel);
    final errorMessage = _buildErrorMessage(formModel);

    return Container(
      width: double.infinity,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: labelWidth,
            padding: const EdgeInsets.only(right: 12),
            alignment: Alignment.centerRight,
            child: _buildLabel(),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [widget.child, if (errorMessage != null) errorMessage],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建垂直布局
  Widget _buildVerticalLayout(EFormModel? formModel) {
    final errorMessage = _buildErrorMessage(formModel);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildLabel(),
        const SizedBox(height: 8),
        widget.child,
        if (errorMessage != null) errorMessage,
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // 在build方法中直接获取表单模型，确保每次构建都使用最新的布局设置
    final formModel = FormModelProvider.maybeOf(context);
    final isHorizontal =
        formModel != null && formModel.layout == EFormLayout.horizontal;

    return Container(
      margin: EdgeInsets.only(bottom: 16),
      child: isHorizontal
          ? _buildHorizontalLayout(formModel)
          : _buildVerticalLayout(formModel),
    );
  }
}

/// 表单项操作工具类
extension EFormItemExtension on BuildContext {
  /// 验证指定表单项
  void validateFormItem(String prop, [String? trigger]) {
    // 从当前上下文开始，向上查找指定prop的EFormItem
    EFormItem? formItemWidget;
    Element? formItemElement;

    // 向上遍历Widget树
    visitAncestorElements((element) {
      if (element.widget is EFormItem) {
        final item = element.widget as EFormItem;
        if (item.prop == prop) {
          formItemWidget = item;
          formItemElement = element;
          return false; // 找到后停止遍历
        }
      }
      return true; // 继续向上查找
    });

    // 如果找到对应的EFormItem并且是StatefulElement，则调用其validate方法
    if (formItemWidget != null && formItemElement is StatefulElement) {
      final statefulElement = formItemElement as StatefulElement;
      final state = statefulElement.state as _EFormItemState;
      state.validate(trigger);
    }
  }

  /// 清除指定表单项的验证状态
  void clearFormItemValidate(String prop) {
    // 从当前上下文开始，向上查找指定prop的EFormItem
    EFormItem? formItemWidget;
    Element? formItemElement;

    // 向上遍历Widget树
    visitAncestorElements((element) {
      if (element.widget is EFormItem) {
        final item = element.widget as EFormItem;
        if (item.prop == prop) {
          formItemWidget = item;
          formItemElement = element;
          return false; // 找到后停止遍历
        }
      }
      return true; // 继续向上查找
    });

    // 如果找到对应的EFormItem并且是StatefulElement，则调用其clearValidate方法
    if (formItemWidget != null && formItemElement is StatefulElement) {
      final statefulElement = formItemElement as StatefulElement;
      final state = statefulElement.state as _EFormItemState;
      state.clearValidate();
    }
  }
}
